import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { TreeSelect, Input, Tooltip, message } from 'antd';
import { TableC, ModalC, SecuritiesCodeC, UploadC, codeType, PrimaryC, PrimaryGhostC, InputNumberC } from '../../../../comps';
import style from '../index.less';
import uuid from 'es6-uuid';
import config from '../../../../comps/business/tradingMarket/config';
import { exportFile } from '../../../../utils/commonFunc';
const FormItem = Form.Item;
@Form.create()
class UploadTableC extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      file: undefined, //文件流
      teplataId: undefined,
      dataSource: [], //标的要素数据源
      dataSourceOld: [], //保存修改之前的每行数据
      page: {
        //当前页码 前端分页
        current: 1,
      },
      zqDataSource: [], //证券/标的代码数据源
      columns: [
        {
          title: (
            <span>
              <label className={style.lableRequire}></label>标的代码
            </span>
          ),
          dataIndex: 'tradingCode',
          key: 'tradingCode',
        },
        {
          title: <span>标的简称</span>,
          dataIndex: 'tradingName',
          key: 'tradingName',
          width: 150,
        },
        {
          title: <span>交易市场</span>,
          dataIndex: 'exchangeCode',
          key: 'exchangeCode',
          width: 150,
        },
        {
          title: <span>所属行业</span>,
          dataIndex: 'industry',
          key: 'industry',
          width: 150,
        },
        {
          title: (
            <span>
              <label className={style.lableRequire}></label>权重
            </span>
          ),
          dataIndex: 'weight',
          key: 'weight',
          width: 120,
        },
        {
          title: '操作',
          dataIndex: 'operation',
          key: 'operation',
          width: 120,
          type: 'operate',
          operates: [
            {
              title: '编辑',
              onClick: (record) => this.editRow(record, 1),
              rules: {
                hide: { relation: 'or', items: [{ key: 'isEdit', value: [true], relation: ['='] }] },
              },
            },
            {
              title: '删除',
              onClick: this.deleteById,
              rules: {
                hide: { relation: 'or', items: [{ key: 'isEdit', value: [true], relation: ['='] }] },
              },
            },
            {
              title: '保存',
              onClick: (record) => this.editRow(record, 2),
              rules: {
                hide: { relation: 'or', items: [{ key: 'isEdit', value: [true], relation: ['!='] }] },
              },
            },
            {
              title: '取消',
              onClick: this.cancle,
              rules: {
                hide: { relation: 'or', items: [{ key: 'isEdit', value: [true], relation: ['!='] }] },
              },
            },
          ],
        },
      ],
      showResult: false, //导入结果弹窗
      uploadData: {}, //上传数据返回
    };
  }

  componentDidMount() {
    this.props.onRef(this);
    this.getZqData(); //获取证券代码（只获取一次）
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.defaultData) != JSON.stringify(this.props.defaultData)) {
      this.setState({
        dataSource: [...nextProps.defaultData],
      });
    }
  }
  //点击提交
  getTableData = () => {
    //判断是否有未保存的数据，
    const { dataSource } = this.state;
    if (!dataSource.length) {
      message.warning('请填写标的要素');
      return;
    }
    for (let index = 0; index < dataSource.length; index++) {
      const item = dataSource[index];
      if (item.isEdit) {
        message.warning('标的要素存在未保存数据');
        return;
      }
    }
    return dataSource;
  };
  //点击保存2或者编辑1
  editRow = (record, flag) => {
    let { dataSource, dataSourceOld } = this.state;
    if (flag == 1) {
      //点击编辑按钮
      dataSource &&
        dataSource.map((item) => {
          if (record.id == item.id) {
            dataSourceOld.push({ ...item }); //保存修改之前的每行数据
            item.isEdit = true;
          }
        });

      this.setState({
        //保存修改之前的每行数据
        dataSourceOld,
        dataSource: [...dataSource],
      });
    } else {
      //点击保存按钮
      if (dataSource) {
        for (let index = 0; index < dataSource.length; index++) {
          const item = dataSource[index];
          if (record.id == item.id) {
            if (record.tradingCode && typeof record.weight == 'number') {
              //标的代码和权重必填
              item.isEdit = false;
            } else {
              message.warning('请填写完整！');
              return;
            }
          }
        }
        const arr = dataSourceOld.filter((item) => item.id != record.id); //删除已保存数据
        this.setState({
          dataSource: [...dataSource],
          dataSourceOld: arr,
        });
      }
    }
  };
  //点击取消按钮
  cancle = (record) => {
    let { dataSourceOld, dataSource } = this.state;
    let oldRow = {};
    dataSourceOld &&
      dataSourceOld.map((item) => {
        //找出编辑之前的数据
        if (record.id == item.id) {
          oldRow = { ...item };
        }
      });
    if (JSON.stringify(oldRow) == '{}') {
      let arr = dataSource && dataSource.filter((item) => item.id != record.id); //当新增的一行 点击取消 就剔除这一行
      this.setState({
        dataSource: [...arr],
      });
      return;
    }
    dataSource &&
      dataSource.map((item) => {
        //替换当前数据
        if (record.id == item.id) {
          for (let i in item) {
            item[i] = oldRow[i];
          }
        }
      });
    const arr = dataSourceOld.filter((item) => item.id != record.id); //删除已保存数据
    this.setState({
      dataSource: [...dataSource],
      dataSourceOld: arr,
    });
  };
  //点击删除按钮
  deleteById = (record) => {
    let { dataSource } = this.state;
    let arr = dataSource.filter((item) => record.id != item.id);
    this.setState({
      dataSource: [...arr],
    });
  };

  //获取标的代码组件初始化数据
  getZqData = () => {
    this.props.dispatch({
      type: 'securitiesCodeM/getSecuritiesList',
      payload: {
        codeType: codeType.gzj,
      },
      callback: (e) => {
        this.setState({
          zqDataSource: e || [],
        });
      },
    });
  };
  //删除行数据
  delete = (e) => {
    const arr = this.state.dataSource.filter((item) => item.id != e.id); //匹配数据
    this.setState({
      dataSource: arr,
    });
  };

  //券池名称改变时恢复标的信息数据
  changePoolName = () => {
    this.setState({
      dataSource: [],
    });
  };

  // 标的证券改变事件
  handleChange = (e, record) => {
    const { dataSource } = this.state;
    const arr = dataSource.filter((item) => item.id == record.id); //匹配数据
    const index = dataSource.findIndex((item) => item.id == record.id); //查找数据位置
    if (e) {
      if (e.tradingCode && e.exchangeCode) {
        //获取对应数据
        arr[0].exchangeCode = e.exchangeCode;
        arr[0].tradingName = e.secuabbr;
        arr[0].tradingCode = e.tradingCode;
        dataSource.splice(index, 1, arr[0]);
        this.setState(
          {
            dataSource,
          },
          () => {
            this.getIndustry(e, arr, index);
          },
        );
      }
    } else {
      arr[0].exchangeCode = undefined;
      arr[0].tradingCode = undefined;
      arr[0].tradingName = undefined;
      dataSource.splice(index, 1, arr[0]);
      this.setState({
        dataSource,
      });
    }
  };

  //查询行业
  getIndustry = (e, arr, index) => {
    const { dispatch } = this.props;
    const { dataSource } = this.state;
    dispatch({
      type: 'CollectingMonitoringM/getIndustry',
      payload: {
        tradingCode: e.tradingCode,
        exchangeCode: e.exchangeCode,
      },
      callback: (res) => {
        if (res) {
          if (res.code == 0) {
            arr[0].industry = res.data?.dataSource?.industry;
            dataSource.splice(index, 1, arr[0]);
            this.setState({
              dataSource,
            });
          } else {
            arr[0].industry = '';
            dataSource.splice(index, 1, arr[0]);
            this.setState({
              dataSource,
            });
          }
        }
      },
    });
  };
  // 新增行
  addRow = () => {
    let dataSource = this.state.dataSource || [];
    dataSource.unshift({
      id: uuid(32),
      isEdit: true,
    });
    this.setState({
      dataSource: [...dataSource],
    });
  };
  //权重改变
  weightChange = (e, record) => {
    let { dataSource } = this.state;
    if (typeof e == 'number') {
      dataSource &&
        dataSource.map((item) => {
          //替换当前数据
          if (record.id == item.id) {
            item.weight = parseFloat(e / 100);
          }
        });
      this.setState({
        dataSource: [...dataSource],
      });
    }
  };

  //改变columns
  changeColumns = () => {
    const {
      form: { getFieldDecorator },
      type,
    } = this.props;
    const { zqDataSource } = this.state;
    const arr = this.state.columns;
    arr.map((item) => {
      if (item.key == 'tradingCode') {
        item.render = (text, record) => {
          let findvalue = config.filter((item) => {
            return item.value == record.exchangeCode;
          });
          if (record.isEdit) {
            return (
              <SecuritiesCodeC
                form={this.props.form}
                initialValue={record.exchangeCode && record.tradingCode ? record.tradingCode + '-' + record.tradingName + '-' + findvalue[0]?.title : ''}
                dataIndex={`code-${record.id}`}
                onChange={(e) => this.handleChange(e, record)}
                titleDisplay={false}
                codeType={codeType.gzj}
                noQueryForInit={true}
                dsFromParent={zqDataSource.length ? zqDataSource : []}
                rules={[{ required: true, message: ' ' }]}
              />
            );
          } else {
            return record.exchangeCode && record.tradingCode ? record.tradingCode + '-' + record.tradingName + '-' + findvalue[0]?.title : '';
          }
        };
      }
      if (item.key == 'tradingName') {
        item.render = (text, record) => {
          if (record.isEdit) {
            return (
              <div style={{ paddingBottom: '5px' }}>
                <Input style={{ width: '100%' }} value={record.tradingName} disabled={true} />
              </div>
            );
          } else {
            return text || '--';
          }
        };
      }
      if (item.key == 'exchangeCode') {
        item.render = (text, record) => {
          let findvalue = config.filter((item) => {
            return item.value == record.exchangeCode;
          });
          if (record.isEdit) {
            return (
              <div style={{ paddingBottom: '5px' }}>
                <Input style={{ width: '100%' }} value={findvalue[0]?.title} disabled={true} />
              </div>
            );
          } else {
            return findvalue[0]?.title || '--';
          }
        };
      }
      if (item.key == 'industry') {
        item.render = (text, record) => {
          if (record.isEdit) {
            return (
              <div style={{ paddingBottom: '5px' }}>
                <Input style={{ width: '100%' }} value={record.industry} disabled={true} />
              </div>
            );
          } else {
            return text || '--';
          }
        };
      }
      if (item.key == 'weight') {
        item.width = 120;
        item.align = 'right';
        item.render = (text, record) => {
          if (record.isEdit) {
            return (
              <div style={{ paddingBottom: '5px' }}>
                <InputNumberC
                  form={this.props.form}
                  precision={2}
                  unit='%'
                  initialValue={record.weight ? parseFloat(record.weight * 100) : undefined}
                  onChange={(e) => this.weightChange(e, record)}
                  dataIndex={record.id}
                  min={0}
                  max={100}
                />
              </div>
            );
          } else {
            return record.weight == 0 || record.weight !== null ? (record.weight * 100).toFixed(2) + '%' : '--';
          }
        };
      }
    });
    return arr;
  };

  //表格分页
  handleTableChange = (current, pageSize) => {
    this.setState({
      page: {
        current: current,
      },
    });
  };
  //模板下载
  dowanloadFile = () => {
    exportFile('gateway/portfolio-server/simulationProduct/download-template');
  };
  //模板上传
  uploadFile = (file) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'CollectingMonitoringM/uploadFile',
      payload: {
        file,
      },
      callback: (uploadData) => {
        if (uploadData) {
          this.setState({
            uploadData,
            showResult: true,
          });
        }
      },
    });
  };
  errorColumnsChange = (columns) => {
    if (columns) {
      columns.map((item) => {
        if (item.key != 'errormessage') {
          item.align = 'center';
        }
      });
    }
    return columns;
  };
  //模板上传模态框
  templateUpLoad = () => {
    const { showResult, uploadData } = this.state;
    let errorColumns = this.errorColumnsChange(uploadData?.errorColumns);
    const modalProps = {
      destroyOnClose: true,
      visible: showResult,
      maskClosable: true,
      title: '提示',
      width: 1000,
      onCancel: () => {
        this.setState({
          showResult: false,
          uploadData: {}, //清空上传数据
        });
      },
      onOk: () => {
        this.setState({
          showResult: false,
          dataSource: uploadData.dataSource || [], //替换标的要素表格
          dataSourceOld: _.cloneDeep(uploadData.dataSource || []),
        });
      },
    };

    return (
      <ModalC {...modalProps}>
        <div className={style.batchUploadOne}>
          共{uploadData?.total}条，其中，导入成功，{uploadData?.success}条；导入失败，{uploadData?.error}条。
        </div>
        <div className={style.batchUpload}>点击取消，重新导入；点击确定，导入成功的标的会自动填充到新建标的列表。</div>
        {uploadData?.error != '0' && <TableC columns={errorColumns} dataSource={uploadData?.errorDataSource} rowKey='id' hidePage={true} />}
      </ModalC>
    );
  };
  render() {
    const { dataSource, page } = this.state;
    const newColumns = this.changeColumns();
    return (
      <div>
        <div className={style.addBtn}>
          <PrimaryC title='新增' onClick={this.addRow} />
          <div>
            <UploadC
              type={2}
              accept='.xlsx,.xls'
              showUploadList={false}
              title={'模板上传'}
              onUpload={(e) => {
                this.uploadFile(e);
              }}
            />
            <PrimaryGhostC title='模板下载' onClick={this.dowanloadFile} />
          </div>
        </div>
        <TableC columns={newColumns} dataSource={dataSource} rowKey='id' current={page.current} pageSizeOptions={['10']} pageSize={10} onPageChange={this.handleTableChange} />
        {this.templateUpLoad()}
      </div>
    );
  }
}

export default connect(({ CollectingMonitoringM, securitiesCodeM }) => ({ CollectingMonitoringM, securitiesCodeM }))(UploadTableC);
